package com.banana.springcloud.loadbalancer.impl;

import com.banana.springcloud.loadbalancer.MyLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义轮询策略
 * @author layman
 * @date 2021/1/16
 */
@Component
public class MyLoadBalancerImpl implements MyLoadBalancer {

    private AtomicInteger nextServerCounter =  new AtomicInteger(0);

    public final int getAndIncrement(){
        int current;
        int next;
        do{
            current = nextServerCounter.get();
            next = (current > Integer.MAX_VALUE ? 0 : current + 1);
        }while(!this.nextServerCounter.compareAndSet(current,next));
        System.out.println("--------次数next的值--------:"+next);
        return next;
    }
    @Override
    public ServiceInstance getInstance(List<ServiceInstance> instances) {
        int index = getAndIncrement() % instances.size();
        return instances.get(index);
    }
}
